"use strict";
$E.softphoneBasePath = 'js/softphone/wscti';
define([$E.softphoneBasePath + '/softphone/softphone.core' + $E.jsv], function(softphone) {
	/**
	 * CallInfo类
	 */
	var CallInfo = function(callInfo){
        for(var k in callInfo){
            this[k] = callInfo[k];
        }
    };
    CallInfo.prototype = {
        getValue : function(key){
            return this[key.toLowerCase()];
        },
        setValue : function(key, value){
            this[key.toLowerCase()] = value;
        }
    };
    
    /**
     * Softphone类
     */
	var Softphone = function() {
		this.initialized = false;
    };
    Softphone.prototype = {
		/**
		 * 初始化软电话，加载config
		 */
    	initSoftphone : function(params, callback) {
    		var a = this;
    		softphone.initSoftphone(function(){
    			a.initialized = true;
    			$F.log('Softphone - initSoftphone', '初始化WSCTI软电话成功');
    			callback && callback(true);
    		}, function(){
    			$F.err('Softphone - initSoftphone', '初始化WSCTI软电话失败');
    			callback && callback(false);
    		}, params);
    	},
        /**
         * 软电话的commonCall
         * @param callName 名字
         * @param callParas 参数
         * @param callback 回调
         */
        simpleCommonCall : function(callName, callParas, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	return softphone.commonCall(callName, callParas, callback);
        },
        /**
         * 获取软电话的callInfo
         * @param callback
         */
        getCallInfo : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var allAttachDatas = softphone.CallInfo.AttachData("^JSON^");
        	var callInfo = new CallInfo({
				agentid : softphone.agentID,
				extension : softphone.extension,
				agentstate : softphone.agentState,
				agentmode: softphone.agentMode,
				evtdetail : softphone.EvtDetail,
				rawattachdata : softphone.CallInfo.RawAttachData,
				callstate : softphone.CallInfo.CallState,
				ani : softphone.CallInfo.ANI,
				dnis : softphone.CallInfo.DNIS,
				otherdn : softphone.CallInfo.OtherDN,
				starttime : softphone.CallInfo.StartTime,
				establishtime : softphone.CallInfo.EstablishTime,
				endtime : softphone.CallInfo.EndTime,
				calltype : softphone.CallInfo.CallType,
				attachdatadisplay : '',
				istranin : softphone.CallInfo.IsTranIn,
				istranout : softphone.CallInfo.IsTranOut,
				hanguptype : softphone.CallInfo.hangupType,
				callid2 : softphone.CallInfo.CallID2,
				callid1 : softphone.CallInfo.CallID1,
				callstate2 : softphone.CallInfo.CallState2,
				event_guid : softphone.CallInfo.Event_GUID,
				transferflag : softphone.CallInfo.transferflag,
				allattachdatas : allAttachDatas,
				callParty: softphone.CallInfo.CallParty
			});
        	if (callback) {
                callback(callInfo);
        	}
        	return callInfo;
        },
        /**
         * 获取callStat
         * @param callback
         */
        getCallStat : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var callStat = {};
			if (softphone && softphone.CallStat) {
				callStat = {
					TotalIB : softphone.CallStat.TotalIB,
					TotalOB : softphone.CallStat.TotalOB,
					TotalIBAnswered : softphone.CallStat.TotalIBAnswered,
					TotalOBReached : softphone.CallStat.TotalOBReached,
					TotalIBDuration : softphone.CallStat.TotalIBDuration,
					TotalOBDuration : softphone.CallStat.TotalOBDuration
				};
			}
			if (callback) {
				callback(callStat);
			}
			return callStat;
        },
        /**
         * 获取agentState和agentMode
         * @param callback
         */
        getAgentStateAndMode : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var agentStateAndMode = {
        		agentState : softphone.agentState,
        		agentMode : softphone.agentMode,
        		reasonCode : softphone.reasonCode
        	};
			if (callback) {
				callback(agentStateAndMode);
			}
        	return agentStateAndMode;
        },
        /**
         * 获取transferOnDialingHold属性值
         * @param callback
         */
        getTransferOnDialingHold : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	if (callback) {
				callback({
					TransferOnDialingHold : softphone.TransferOnDialingHold
				});
			}
        	return softphone.TransferOnDialingHold;
        },
        /**
         * 获取事件详细值
         * @param callback
         */
        getEvtDetail : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	if (callback) {
				callback({
					EvtDetail : softphone.EvtDetail
				});
			}
        	return softphone.EvtDetail;
        },
        /**
         * 获取事件
         * @param callback
         */
        getEvent : function(callback) {
            this.simpleCommonCall("getevent", "", callback);
        },
        /**
         * 退出
         * @param callback
         */
        quit : function(callback) {
        	if (!this.softphoneReady()) {
            	if (callback) {
            		callback({ret : "false"});
            	}
        		return false;
        	}
        	softphone.QuitSoftphone();
        	if (callback) {
        		callback({ret : "success"});
        	}
        },

        /**
         * 拨打电话
         * @param number 电话号码
         * @param sData 随路数据
         * @param callback 回调
         */
        makeCall : function(number, sData, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var ret = softphone.makeCall(number, sData);
			callback && callback(ret);
        },
        /**
         * 挂断电话
         * @param callback
         */
        releaseCall : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var ret = softphone.releaseCall();
			callback && callback(ret);
        },
        /**
         * 接起电话
         * @param callback
         */
        answerCall : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.answerCall();
			callback && callback();
        },
        /**
         * 保持电话
         * @param callback
         */
        holdCall : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var ret = softphone.holdCall();
			callback && callback(ret);
        },
        /**
         * 接回电话
         * @param callback
         */
        retrieveCall : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var ret = softphone.retrieveCall();
			callback && callback(ret);
        },
        /**
         * 发起会议
         * @param number 会议号码
         * @param sData 随路数据
         * @param callback
         */
        initConference : function(number, sData, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var ret = softphone.initConference(number, sData);
			callback && callback(ret);
        },
        /**
         * 完成会议
         * @param callback
         */
        completeConference : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var ret = softphone.completeConference();
			callback && callback(ret);
        },
        /**
         * 发起转接
         * @param number 转接号码
         * @param sData 随路数据
         * @param callback
         */
        initTransfer : function(number, sData, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var ret = softphone.initTransfer(number, sData);
			callback && callback(ret);
        },
        /**
         * 完成转接
         * @param callback
         */
        completeTransfer : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var ret = softphone.completeTransfer();
			callback && callback(ret);
        },
        /**
         * 直接转
         * @param number 转接号码
         * @param sData 随路数据
         * @param callback
         */
        muteTransfer : function(number, sData, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.muteTransfer(number, sData);
			callback && callback();
        },
        /**
         * 单步转
         * @param number 转接号码
         * @param sData 随路数据
         * @param callback
         */
        singleStepTransfer : function(number, sData, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.singleStepTransfer(number, sData);
			callback && callback();
        },
        /**
         * 取消转接或者会议
         * @param callback
         */
        reconnect : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.reconnect();
			callback && callback();
        },
        /**
         * 置闲
         * @param callback
         */
        ready : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.agentReady();
        	callback && callback();
        },
        /**
         * 置忙
         * @param callback
         */
        notReady : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.agentNotReady();
			callback && callback();
        },
        /**
         * 小休
         * @param reasonCode
		 * @param callback
         */
        notReady2 : function(reasonCode, callback) {
        	softphone.agentNotReady2(3, reasonCode);
        },
        /**
         * 小休
         * @param callback
         */
        breaks : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.agentNotReady2();
        },
		/**
		 * acw
		 * @param callback
		 */
		acw : function(callback) {
			if (!this.softphoneReady()) {
				return false;
			}
			softphone.acw();
			callback && callback();
		},
        /**
         * 静音
         * @param callback
         */
        mute : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.mute();
        	if (callback) {
        		callback();
        	}
        },
        /**
         * 取消静音
         * @param callback
         */
        unMute : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.unmute();
        	if (callback) {
        		callback();
        	}
        },
        /**
         * 通知软电话工作开始
         * @param workStatus
         * @param callback
         */
        notifyWorkStart : function(workStatus, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.notifyWorkStart(workStatus);
        	if (callback) {
        		callback();
        	}
        },
        /**
         * 通知软电话工作结束
         * @param callback
         */
        notifyWorkEnd : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.notifyWorkEnd();
        	if (callback) {
        		callback();
        	}
        },
        /**
         * 获取所有的随路数据
         * @param callback
         */
        allAttachDatas : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var allAttachDatas = softphone.CallInfo.AttachData("^JSON^");
			if (callback) {
				callback(allAttachDatas);
			}
			return allAttachDatas;
        },
        /**
         * 根据给定key获取随路数据
         * @param key
         * @param callback
         */
        attachData : function(key, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var attachData = softphone.CallInfo.AttachData(key);
        	if (callback) {
				callback(attachData);
			}
			return attachData;
        },
        /**
         * 获取工号
         * @param callback
         */
        getAgentId : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var agentId = softphone.agentId;
        	if (callback) {
        		callback({
        			agentId: agentId
        		});
        	}
        	return agentId;
        },
        /**
         * 获取分机
         * @param callback
         */
        getExtension : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var extension = softphone.dn;
        	if (callback) {
        		callback({
        			extension: extension
        		});
        	}
        	return extension;
        },
        /**
         * 获取录音guid
         * @param callback
         */
        getRecordGuid : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var recordGuid = softphone.Recording_GUID;
        	if (callback) {
        		callback({
        			recordGuid: recordGuid
        		});
        	}
        	return recordGuid;
        },
        
        /**
         * 获取录音相关信息
         * @param callback
         */
        getRecordInfo : function(callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	var recordGuid = softphone.Recording_GUID,
        		recordFile = softphone.Recording_File,
        		recordFlag = softphone.RecordingFlag;
        	if (callback) {
        		callback({
        			recordGuid: recordGuid,
        			recordFile: recordFile,
        			recordFlag: recordFlag
        		});
        	}
        	return recordGuid;
        },
        /**
         * 强退
         * @param dn
         * @param agentId
         * @param callback
         */
        forceAgentLogout : function(dn, agentId, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.forceAgentLogout(dn, agentId, callback);
        },
        /**
         * 强忙
         * @param dn
         * @param agentId
         * @param callback
         */
        forceAgentNotReady : function(dn, agentId, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.forceAgentNotReady(dn, agentId, callback);
        },
        /**
         * 强闲
         * @param dn
         * @param agentId
         * @param callback
         */
        forceAgentReady : function(dn, agentId, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.forceAgentReady(dn, agentId, callback);
        },
        /**
         * 监听
         * @param dn
		 * @param agentId
         * @param callback
         */
        listen : function (dn, agentId, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.listen(dn, agentId, callback);
        },
        /**
         * 强拆
		 * @param dn
         * @param agentId
         * @param callback
         */
        intercept : function (dn, agentId, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.intercept(dn, agentId, callback);
        },
        /**
         * 强断
         * @param dn
         * @param callback
         */
        forceDisconnectAgentByDN : function (dn, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.forceDisconnectAgentByDN(dn, undefined, callback);
        },
        /**
         * 板卡挂断
		 * @param dn
		 * @param agentId
         * @param callback
         */
        forceHangUp : function (dn, agentId, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.forceHangup(dn, agentId, callback);
        },
        /**
         * 强插
         * @param dn
		 * @param agentId
         * @param callback
         */
        bargeIn : function (dn, agentId, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.bargeIn(dn, agentId, callback);
        },
        /**
         * 拦截
         * @param dn
         * @param agentId
         * @param callback
         */
        takeOver : function (dn, agentId, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.takeOver(dn, agentId, callback);
        },
        /**
         * 暗语
         * @param dn
         * @param agentId
         * @param callback
         */
        coach : function (dn, agentId, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.coach(dn, agentId, callback);
        },

        /**
         * 设置软电话自动应答属性
         * @param autoAnswer
         */
        setAutoAnswer : function(autoAnswer) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.autoAnswer = autoAnswer;
        },
        
        /**
         * 获取软电话自动应答值
         * @param callback
         */
        getAutoAnswer : function(callback) {
        	if (!this.softphoneReady()) {
        		callback && callback();
        	} else {
        		callback && callback(softphone.autoAnswer);
        	}
        },
        
        /**
         * 设置软电话自动添加号码头
         * @param autoPrefix
         */
        setAutoPrefix : function(autoPrefix) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.autoPrefix = autoPrefix;
        },
        
        /**
         * 获取软电话自动添加号码头
         * @param callback
         */
        getAutoPrefix : function(callback) {
        	if (!this.softphoneReady()) {
        		callback && callback();
        	} else {
        		callback && callback(softphone.autoPrefix);
        	}
        },
        
        /**
         * 发送DTMF数据
         * @param number
         * @param callback
         */
        sendDTMF : function(number, callback) {
        	if (!this.softphoneReady()) {
        		return false;
        	}
        	softphone.sendDTMF(number);
            if (callback) {
            	callback();
            }
        },
        
        /**
         * 给软电话注册vblocalproxy事件
         * @param callback 回调函数 接收参数data
         * 主要分为：
         * 1.data.type === "SCTIEvent" SCTIEvent事件
         *      包括了：data.msg == 'callstatechange' 电话状态变化
         *              data.msg == 'agentstatechange' 坐席状态变化
         *              data.msg == 'OnCallStart' 电话开始
         *              data.msg == 'OnCallEstablish' 电话接起
         *              data.msg.startWith('OnCallAction') 一些电话行为，包括了：MakeCall，InitTransfer，InitConference，MuteTransfer，SingleStepTransfer，PhoneNo
         *              data.msg == 'OnCallEnd' 电话结束
         *              data.msg == '73' notready
         *              data.msg == '74' EVT_DATAUPDATED
         *              data.msg == '23' mute
         *              data.msg == '24' unmute
         *
         * 2.data.type === "CTIEvent" CTIEvent事件
         *      CTIEvent相较于SCTIEvent来说，更底层，更全面，其中的参数也需要自己解析，解析过程可以自己尝试打印出内容查看后自行解析。主要用到了：
         *          var parsedEvent = parseEventDetail(data.EvtDetail);//解析事件详细内容
                    var evtObj = parsedEvent.evtObj;//事件内容
                    var attachObj = parsedEvent.attachObj;//随路数据
         *          evtObj["event"] == "9"  partydeleted
         *          evtObj["event"] == "22" partychanged
         *
         * 3.data.type === 'inited'
         *      电话初始化成功后事件
         */
        addEventListener : function(callback) {
        	if (callback) {
        		softphone.addEvtListener('softphone.api', 'OnSCTIEvent', function(data){
        			var callInfo = softphone.CallInfo;
        			var sfInfo = {
    					ani : callInfo.ANI,
    					dnis : callInfo.DNIS,
    					agentid : softphone.agentID,
    					extension : softphone.extension,
    					agentstate : softphone.AgentState,
    					evtdetail : softphone.EvtDetail,
    					calltype : callInfo.CallType,
    					attachdatadisplay : ''
    				};
        			callback({
        				type: 'SCTIEvent',
        				msg: data,
        				sfInfo: sfInfo
        			});
        		});
            	softphone.addEvtListener('softphone.api', 'OnOrigCTIEvent', function(data){
        			callback({
        				type: 'CTIEvent',
        				msg: data
        			});
        		});
            }
        },
        
        /**
         * 软电话是否可用
         * @returns {Boolean}
         */
        available : function() {
        	if (softphone) {
        		return true;
        	}
        	return false;
        },
        
        /**
         * 软电话登录
         * @param param 登录参数，是一个json对象
         *  {
                agentId : agentId, 		// 工号
                extension : extension, 	// 分机
                queue : queue,  		// 队列
                position : position, 	// 位置
                password : password, 	// 密码
                pds: {},                // 预测外呼相关参数
                loginType: loginType    // 签入类型
            }
         * @param callback 登录结果回调，参数result: {true|false}
         */
        login : function(param, callback) {
        	softphone.login2(Object.assign(param, {
        		dn: param.extension,
				pds: param.pds || {},
        		callback: callback
        	}));
        },
        
        /**
         * 软电话登出
         */
        logout : function(callback) {
        	softphone.agentLogout({
				callback: callback
			});
        },
        
        getIniInfo : function(callback) {
        	var iniInfo = {};
			iniInfo.NeedAgentID = softphone.commonCall("GetiniValue", "[CTI]NeedAgentID");
			iniInfo.NeedPassword = softphone.commonCall("GetiniValue", "[CTI]NeedPassword");
			iniInfo.NeedExtension = softphone.commonCall("GetiniValue", "[CTI]NeedExtension");
			iniInfo.NeedQueue = softphone.commonCall("GetiniValue", "[CTI]NeedQueue");
			iniInfo.NeedQueueExt = softphone.commonCall("GetiniValue", "[CTI]NeedQueueExt");
			iniInfo.QueueMultiSelect = softphone.commonCall("GetiniValue", "[CTI]QueueMultiSelect");
			iniInfo.NeedPosition = softphone.commonCall("GetiniValue", "[CTI]NeedPosition");
			iniInfo.AgentID = softphone.commonCall("GetiniValue", "[CTI]AgentID");
			iniInfo.Extension = softphone.commonCall("GetiniValue", "[CTI]Extension");
			iniInfo.NeedPDS = softphone.commonCall("GetiniValue", "[CTI]NeedPDS");
			if (callback) {
				callback(iniInfo);
			}
			return iniInfo;
        },
        
        softphoneReady : function() {
        	if (this.available) {
        		if (this.initialized) {
            		return true;
            	}
        	}
        	return false;
        },

		core: function() {
        	return softphone;
		}
    };
	
	return Softphone;
});


